package com.suse.jd_system_server.aspect;

import com.suse.jd_system_server.annotation.logWeaving;
import com.suse.jd_system_server.dao.LogDao;
import com.suse.jd_system_server.entity.Logs;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 日志管理切面类
 * 当目标切点进行了对表的操作之后，通过传来的操作者和操作动作构成日志，传入日志表
 */
@Component
@Aspect
public class logAspect {
    @Autowired
    private LogDao logDao;

    @Autowired
    private HttpServletRequest request;


    /**
     * 切点所在，先指向自定义注解，再通过自定义注解指向不同的切点，自定义注解的作用更像切面与切点之间的”暂存区“，通过注解可以作用于不同的切点，也可以理解为切面和切点的织入媒介
     */
    @Pointcut("@annotation(com.suse.jd_system_server.annotation.logWeaving)")
    void log(){}
    /**
     * 作用：获取操作者信息，完成对数据库日志表的插入操作
     */
    @After("log()")
    public void doLog(JoinPoint joinPoint) throws NoSuchFieldException {
        //准备一个log实体
        Logs log = new Logs();

        //获取用户信息，用户信息在登录存入session
        String userName = (String) request.getSession().getAttribute("userName");
        Long userId = (Long) request.getSession().getAttribute("userId");
//        System.out.println("userName:"+userName);
//        System.out.println("userId:"+userId);

        //获取用户操作信息。通过反射注解中的value获取
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        logWeaving annotation = method.getAnnotation(logWeaving.class);
        String value = annotation.value();

        //完成实体封装
        log.setLogMessage(userName+"完成了"+value);
        log.setUserId(userId);

        //数据插入
        logDao.insertLog(log);

    }

}
